//
//  APIManager.swift
//  Kool Car
//
//  Created by huangweiqiang on 2021/12/16.
//

import UIKit
import Moya
import Alamofire
import Accelerate


enum APIManager {
    
    case hotArticle//热门咨询列表
    case articleCategoryList//咨询栏目-附带4篇文章
    case memberRegister(param: Any) //注册
    case consultationList(param: Any)//咨询栏目-咨询列表（分页）
    case getAppVersion(param: Any)//获取当前版本号
    case captchaGetCode(param: Any) //发送SMS短信验证码
    case captchaVerify(param: Any) //校验验证码
    case cloudRegist(param: Any)    //注册
    case login(param: Any)          //登录
    case updatePwd(param: Any)       //更新密码接口
    case massagesList(param: Any) //站内讯息列表
    case massagesDetail(param: Any) //站内讯息详情
    case massagesUpdateFlag(param: Any) //站内讯息更新已读标识
    case carinsurance //APP车保-查看内容
    case articleList(param: Any)//车保-查看
    case promotionzActivity//当前用户获得的推广活动
    case getDetailspromotion(param: Any)//查询推广活动的详情
    case shareActivities(param: Any)//分享推广活动
    case getSignIn//签到领积分
    case getShareCouponIntegral(param: Any)//领取分享的推广活动积分
    case hotVehicle//我要买车-热门车辆
    case carListData//我要买车-车型列表
    case recommandCarsPage(param: Any)//我要买车-推荐车辆带分页列表
    case recommandCars//我要买车-推荐车辆
    case favorite(param: Any)//我要买车-收藏或取消收藏
    case browsingHistory(param: Any)//保存浏览记录
    case getGoodsBrowse(param: Any)//浏览记录分页列表
    case clearBrowsingHistory//清空浏览记录
    case allBrandSerisesInfo //查询所有的品牌和车系
    case carDetailsData(param: Any)//车辆详情
    case getProductList(param: Any)//商品列表
    case flashCale//限时抢购单列表
    case favoriteProduct(param: Any)//商城-登录状态点击商品收藏或取消收藏
    case moreFlashSaleList(param: Any)//限时抢购-更多-分页列表
    
    case getArticleList(param: Any)//文章专题
    case updateUserInfo(param: Any)//修改用户信息个人资料
    case modifyPassword(param: Any)//修改用户密码
    case indexAboutUs //关于我们
    case apiArticleDetail(param: Any) //文章详情
    case usedcarOrder(param: Any) //车辆预定
    case usedcarOrderList(param: Any)//订单列表
    case createOrder(param: Any) //创建订单
    case paymentDetail(param: Any) //支付结果信息
    case contactUs(param: Any) //联系我们
    case orderAgreement(param: Any) //订购协议
    case memberGreement(param: Any) //用户协议
    case privacyGreement(param: Any) //隐私政策
    case indexLegalStatement //法律声名
    case indexCompany(param: Any) //公司简介
    case baseParameter(param: Any) //基础参数 setting
    case recycleOrderSave(param: Any) //回收单提交
    case maintainOrderSave(param: Any) //提交维修单
    case ossUploadImage(imageData: Data) //OSS上传图片
    case usedcarList(param: Any) //所有车辆列表-不分页
    case userdCarPage(param: Any) //选车页：所有车辆列表-分页
    case selectparameter(param: Any) //车辆查询预选参数接口
    case cateBrandSerisesInfo(param: Any) //品牌车系参数
    case userdRecommand//车辆推荐
    case memberGetDetail //用户详情
    case getQuickMark //会员二维码
    case getCouponcodeData(param: Any)//我的优惠券
    case getCouponcodeDataNew(param: Any)//我的优惠券V2
    case getOSSToken //获取OSS临时授权
    case getMassages(param: Any)//分页查询消息
    case getMassagesDetail(param: Any)//查询消息详情
    case getBrandSerisesInfo //查询品牌和车系
    case getEstimateCar(param: Any)//回收估价

    
    case integralProductPage(param: Any) //积分商品列表
    case createIntegralOrder(param: Any) //兑换积分商品
    case integralOrderPage(param: Any) //积分商品订单列表
    case getHistoryInfo(param: Any)//获取结算页数据
    case createServerOrder(param: Any)//结算提交订单
    case getProductPage(param: Any)//商品列表查询
    case getCategoryList(param: Any)//商品类型查询接口
    case getProductDetail(param: Any)//商品详情
    case productCollect(param: Any)//商品收藏
    case addShoppingCart(param: Any)//购物车添加商品
    case getShoppingCartList(param: Any)//我的购物车列表
    case removeAllCart(param: Any)//清空购物车
    case removeSingleCartGoods(param: Any)//购物车商品删除
    case productOrder(param: Any)//订单信息预览
    case productSubmit(param: Any)//提交订单
    case getCurrentNum(param: Any)//查询当前商品购物车数量
    case productOrderDetail(param: Any)//订单详情
    case myFavoriteProduct(param: Any)//我的收藏（商品）
    case cartDAddNum(param: Any)//增加购物车商品数量
//    case moreFlashCale(param: Any)//秒杀活动专场列表
    case getFlashSale(param: Any)//获取活动信息
    case carIntegrate(param: Any)//购物车内容整合
    case getAboutCategoryList//获取底部栏目
    case getListVerbose(param: Any)//文章及栏目查询
    case getLastInfo//获取上次估价
    case carOrderGetLastInfo(param: Any)//上次车辆下单信息
    case cancelMember(param: Any)//注销账号
    case commonMmemberVerify(param: Any) //验证手机号是否存在
    case commonMemberAreaCode(param: Any) //手机区号
    case couponCodePageV3(param: Any) //优惠券列表
    case codeExchange(param: Any) //兑换优惠券
    case logoutAccountAgreement //注销账号协议
    /**
     articleCode 返回所有协议内容
     参数：
     專業車輛產品檢定認證  == COMPANY_4
     會員通訊  == MEMBERSAREA_1
     貼心優惠  == MEMBERSAREA_2
     專屬活動  == MEMBERSAREA_3
     緊急支援  == EMERGENCYSUPPORT_1
     */
    case articleCode(param: Any) //回所有协议内容
    
    case indexBaseDetail // 客服热线、公司介绍、服务理念
    case logoutAccount(param: Any) //注销
    case logoutAccountNote //注册提示
    case couponCodeCodeExchange(param: Any) //优惠码兑换券
    case memberIntegralPage(param: Any) //积分记录
    case indexPointsRule(param: Any) //积分使用规则
    case integralProductIntegralTips //积分奖赏顶部滚动提示
    case myFavoritePage(param: Any) //收藏-车辆列表
    case myFavoriteProductPage(param: Any) //收藏-商品列表
    case myCartListNum(param: Any) //获取购物车商品数量
    case bookingAvailabilityList //首页当月日历预约数据展示
    case bookingAvailabilitySelectDay(param: Any) //单个日历可预约时间段
    case serverProductPage(param: Any) //可预约服务列表
    case bookingOrderManagerCreateServerOrder(param: Any) //点击发起预约服务订单
    case commonIndexDetail //PC首页获取门店接口
    case bookingOrderManagerPage(param: Any) //查询我的预约单列表
    case bookingOrderManagerDetail(param: Any)//预约单详情
    case bookingOrderManagerUpdate(param: Any) //取消预约
    
    case goonetcarSelectparameter(param: Any) //车辆列表筛选条件选项
    case goonetcarUserdCarPage(param: Any) //日本车车辆列表
    case goonetcarDetail(param: Any) //海外车车辆详情
    case goonetcarUserdRecommand(param: Any) //热门车
    
}

extension APIManager: Moya.TargetType {
    var headers: [String : String]? {
        //return ["Content-Type":"application/json;charset=utf-8"]
        var tempToken = UserModule.shared.token ?? ""
        if tempToken != "" && (UserModule.shared.token?.count)! > 10 {
            let jsonDict = XTManageCenter.jwtDecode(dataString: tempToken)
            if jsonDict.count > 0, let expTime = jsonDict["exp"] as? NSInteger{
                //说明转换成功
                let date = NSDate.init(timeIntervalSinceNow: 0)
                let nowTimeInterval = NSInteger(date.timeIntervalSince1970) //当前的时间戳
                if expTime - nowTimeInterval > 0 {
                    //未过期 要添加 AccessToken
                }else{
                    tempToken = ""
                    UserModule.shared.token = ""
                    UserModule.shared.isLogined = false
                }
            }
        }
        
        var paramDict: [String: String] = [:]
        var language = "cn"//繁体
        let localSet = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAppLanguage)
        if localSet.contains("en") {
            language = "en"// 英文
        }else if localSet.contains("zh-Hans") {
            language = "sc"//简体
        }
        paramDict["language"] = language
        
        if self.path.contains("memberLogin") {
            paramDict["Content-Type"] = "application/json"
        }
        
        let token = UserModule.shared.token ?? ""
        if token != "" {
            //paramDict["_koolcar"] = token
            paramDict["Cookie"] = String(format: "_koolcar=%@", token)
            //paramDict["token"] = String(format: "_koolcar=%@", token)
        }else{
            //paramDict["_koolcar"] = ""
            paramDict["Cookie"] = ""
            //paramDict["token"] = ""
        }
        
       
        
        
        return paramDict
    }
    
    var baseURL: URL {
        return URL.init(string: ServerConfig.requestUrl())!
    }
    
    var path: String {
        switch self {
        case .login:
            return "/memberLogin"
        case .updatePwd:
            return "/cloud/common/updatePwd"
        case .captchaGetCode:
            return "/cloud/common/captcha/getCode"
        case .cloudRegist:
            return "/cloud/common/regist"
        case .captchaVerify:
            return "/cloud/common/captcha/verify"
        case .massagesList:
            return "/cloud/api/massages/page"
        case .massagesDetail:
            return "/cloud/api/massages/detail"
        case .massagesUpdateFlag:
            return "/cloud/api/massages/updateFlag"
        case .carinsurance:
            return "/cloud/common/index/carinsurance"
        case .articleList:
            return "/cloud/admin/article/list"
        case .consultationList:
            return "/cloud/common/apiArticle/page"
        case .promotionzActivity:
            return "/cloud/api/popularize/popularizeCoupon"
        case .getDetailspromotion:
            return "/cloud/common/index/popularizeCouponInfo"
        case .shareActivities:
            return "/cloud/api/popularize/shareCoupon"
        case .getSignIn:
            return "/cloud/api/member/signReward"
        case .getShareCouponIntegral:
            return "/cloud/api/popularize/getShareCoupon"
        case .hotVehicle:
            return "/cloud/common/usedcar/userdRecommand"
        case .carListData:
            return "/cloud/common/usedcar/getCarCategoryList"
        case .recommandCarsPage:
            return "/cloud/common/usedcar/userdCarPage"
        case .recommandCars:
            return "/cloud/common/usedcar/recommandCars"
        case .favorite:
            return "/cloud/api/favorite/interest"
        case .browsingHistory:
            return "/cloud/api/browsingHistory/save"
        case .getGoodsBrowse:
            return "/cloud/api/browsingHistory/page"
        case .clearBrowsingHistory:
            return "/cloud/api/browsingHistory/removeAll"
        case .carDetailsData:
            return "/cloud/common/usedcar/detail"
        case .recycleOrderSave:
            return "/cloud/common/recycleOrder/appSave"
        case .getProductList:
            return "/cloud/common/product/page"
        case .getCategoryList:
            return "/cloud/common/product/categoryList"
        case .flashCale:
            return "/cloud/common/promotion/info"
        case .favoriteProduct:
            return "/cloud/api/favorite/interestProduct"
        case .moreFlashSaleList:
            return "/cloud/common/promotion/page"
            
            
        case .getArticleList:
            return "/cloud/common/apiArticle/list"
        case .updateUserInfo:
            return "/cloud/api/member/update"
        case .modifyPassword:
            return "/cloud/api/member/modifyPassword"
        case .indexAboutUs:
            return "/cloud/common/index/aboutUs"
        case .apiArticleDetail:
            return "/cloud/common/apiArticle/detail"
        case .usedcarOrder:
            return "/cloud/api/usedcarOrder/reserve"
        case .usedcarOrderList:
            return "/cloud/api/usedcarOrder/page"
        case .createOrder:
            return "/cloud/common/payment/create"
        case .paymentDetail:
            return "/cloud/common/payment/detail"
        case .orderAgreement:
            return "/cloud/common/index/orderAgreement"
        case .memberGreement:
            return "/cloud/common/index/memberGreement"
        case .privacyGreement:
            return "/cloud/common/index/privacyGreement"
        case .indexLegalStatement:
            return "/cloud/common/index/legalStatement"
        case .contactUs:
            return "/cloud/common/index/contactUs"
        case .indexCompany:
            return "/cloud/common/index/company"
        case .baseParameter:
            return "/cloud/common/index/baseParameter"
       
        case .maintainOrderSave:
            return "/cloud/common/maintainOrder/save"
        case .ossUploadImage:
            return "/cloud/common/aliyunStorage/upload"
        case .usedcarList:
            return "/cloud/common/user/usedcarList"
        case .userdCarPage:
            return "/cloud/common/usedcar/userdCarPage"
        case .selectparameter:
            return "/cloud/common/usedcar/selectparameter"
        case .cateBrandSerisesInfo:
            return "/cloud/common/index/brandSerisesInfo"
        case .memberGetDetail:
            return "/cloud/api/member/getDetail"
        case .getQuickMark:
            return "/cloud/api/member/getQuickMark"
        case .getCouponcodeData:
            return "/cloud/api/couponCode/page"
        case .getOSSToken:
            return "/cloud/common/aliyunStorage/getToken"
        case .getMassages:
            return "/cloud/api/massages/page"
        case .getMassagesDetail:
            return "/cloud/api/massages/detail"
        case .articleCode:
            return "/cloud/common/article/code"
        case .integralProductPage:
            return "/cloud/common/integralProduct/page"
        case .createIntegralOrder:
            return "/cloud/common/integralProduct/createIntegralOrder"
        case .integralOrderPage:
            return "/cloud/common/integralProduct/integralOrderPage"
        case .getBrandSerisesInfo:
            return "/cloud/common/index/brandSerisesInfo"
        case .getEstimateCar:
            return "/cloud/common/recycleOrder/estimateCar"
        case .allBrandSerisesInfo:
            return "/cloud/common/index/allBrandSerisesInfo"
      
        case .getHistoryInfo:
            return "/cloud/common/serverProduct/getHistoryInfo"
        case .createServerOrder:
            return "/cloud/common/serverProduct/createServerOrder"
        case .getProductPage:
            return "/cloud/common/product/page"
        case .getProductDetail:
            return "/cloud/common/product/detail"
        case .productCollect:
            return "/cloud/api/favorite/interestProduct"
        case .addShoppingCart:
            return "/cloud/common/cart/add"
        case .getShoppingCartList:
            return "/cloud/common/cart/myCartList"
        case .removeAllCart:
            return "/cloud/common/cart/removeAll"
        case .removeSingleCartGoods:
            return "/cloud/common/cart/remove"
        case .productOrder:
            return "/cloud/common/product/previewProductOrder"
        case .productSubmit:
            return "/cloud/common/product/submit"
        case .getCurrentNum:
            return "/cloud/common/cart/getCurrentNum"
        case .productOrderDetail:
            return "/cloud/api/usedcarOrder/productOrderDetail"
        case .myFavoriteProduct:
            return "/cloud/api/favorite/myFavoriteProduct"
        case .cartDAddNum:
            return "/cloud/common/cart/addNum"
//        case .moreFlashCale:
//            return "/cloud/common/promotion/page"
        case .getFlashSale:
            return "/cloud/common/promotion/detail"
        case .carIntegrate:
            return "/cloud/common/cart/integrate"
        case .getAboutCategoryList:
            return "/cloud/common/apiArticle/articleCategoryListForBottom"
        case .getListVerbose:
            return "/cloud/common/apiArticle/listVerbose"
        case .userdRecommand:
            return "/cloud/common/usedcar/userdRecommand"
        case .getLastInfo:
            return "/cloud/common/recycleOrder/getLastInfo"
        case .carOrderGetLastInfo:
            return "/cloud/api/usedcarOrder/getLastInfo"
        case .cancelMember:
            return "/cloud/common/cancel_member"
        case .getCouponcodeDataNew:
            return "/cloud/api/couponCode/pageV2"
        case .memberRegister:
            return "/cloud/common/member/register"
        case .hotArticle:
            return "/cloud/common/apiArticle/app/hotArticle"
        case .articleCategoryList:
            return "/cloud/common/apiArticle/app/articleCategoryList"
        case .getAppVersion:
            return "/cloud/common/appVersion/curr"
        case .commonMmemberVerify:
            return "/cloud/common/member/verify"
        case .commonMemberAreaCode:
            return "/cloud/common/member/areaCode"
        case .couponCodePageV3:
            return "/cloud/api/couponCode/pageV3"
            case .codeExchange:
                return "/cloud/api/couponCode/on/codeExchange"
            case .indexBaseDetail:
                return "/cloud/common/index/baseDetail"
            case .logoutAccount:
                return "/cloud/common/logoutAccount"
            case .logoutAccountNote:
                return "/cloud/common/index/logoutAccountNote"
            case .couponCodeCodeExchange:
                return "/cloud/api/couponCode/codeExchange"
            case .memberIntegralPage:
                return "/cloud/api/member/memberIntegralPage"
            case .indexPointsRule:
                return "/cloud/common/index/pointsRule"
            case .integralProductIntegralTips:
                return "/cloud/common/integralProduct/integralTips"
            case .logoutAccountAgreement:
                return "/cloud/common/index/logoutAccountAgreement"
            case .myFavoritePage:
                return "/cloud/api/favorite/myFavoritePage"
            case .myFavoriteProductPage:
                return "/cloud/api/favorite/myFavoriteProductPage"
            case .myCartListNum:
                return "/cloud/common/cart/myCartListNum"
            case .bookingAvailabilityList:
                return "/cloud/api/bookingAvailability/list"
            case .bookingAvailabilitySelectDay:
                return "/cloud/api/bookingAvailability/selectDay"
            case .serverProductPage:
                return "/cloud/common/serverProduct/page"
            case .bookingOrderManagerCreateServerOrder:
                return "/cloud/api/bookingOrderManager/createServerOrder"
            case .commonIndexDetail:
                return "/cloud/common/index/detail"
            case .bookingOrderManagerPage:
                return "/cloud/api/bookingOrderManager/page"
            case .bookingOrderManagerDetail:
                return "/cloud/api/bookingOrderManager/detail"
            case .bookingOrderManagerUpdate:
                return "/cloud/api/bookingOrderManager/update"
            case .goonetcarSelectparameter:
                return "/cloud/common/goonetcar/selectparameter"
            case .goonetcarUserdCarPage:
                return "/cloud/common/goonetcar/userdCarPage"
            case .goonetcarDetail:
                return "/cloud/common/goonetcar/detail"
            case .goonetcarUserdRecommand:
                return "/cloud/common/goonetcar/userdRecommand"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .login,
                .updatePwd,
                .massagesUpdateFlag,
                .updateUserInfo,
                .modifyPassword,
                .usedcarOrder,
                .recycleOrderSave,
                .maintainOrderSave,
                .ossUploadImage,
                .getOSSToken,
                .createIntegralOrder,
                .createServerOrder,
                .productCollect,
                .addShoppingCart,
                .removeAllCart,
                .removeSingleCartGoods,
                .productSubmit,
                .cartDAddNum,
                .carIntegrate,
                .memberRegister,
                .shareActivities,
                .favorite,
                .browsingHistory,
                .clearBrowsingHistory,
                .favoriteProduct,
                .logoutAccount,
                .bookingOrderManagerCreateServerOrder,
                .bookingOrderManagerUpdate,
                .cloudRegist:
            return .post
        default:
            return .get
        }
    }
    
    //用于单元测试
    var sampleData: Data {
        return "".data(using: .utf8)!
    }
    
    //在 task 中使用 requestCompositeParameters ，可以同时设置 bodyParameters 和 urlParameters
    var task: Task {
        switch self {
            //参数放在Query
        case .captchaGetCode(let param),
                .updatePwd(let param),
                .captchaVerify(let param),
                .massagesList(let param),
                .massagesDetail(let param),
                .massagesUpdateFlag(let param),
                .articleList(let param),
                .getDetailspromotion(let param),
                .getShareCouponIntegral(let param),
                .recommandCarsPage(let param),
                .getGoodsBrowse(let param),
                .carDetailsData(let param),
                .getProductList(let param),
                .moreFlashSaleList(let param),
            
                .getArticleList(let param),
                .apiArticleDetail(let param),
                .usedcarOrderList(let param),
                .createOrder(let param),
                .paymentDetail(let param),
                .orderAgreement(let param),
                .memberGreement(let param),
                .privacyGreement(let param),
                .contactUs(let param),
                .indexCompany(let param),
                .baseParameter(let param),
                .usedcarList(let param),
                .userdCarPage(let param),
                .selectparameter(let param),
                .cateBrandSerisesInfo(let param),
                .getCouponcodeData(let param),
                .getMassages(let param),
                .getMassagesDetail(let param),
                .articleCode(let param),
                .integralProductPage(let param),
                .integralOrderPage(let param),
                .createIntegralOrder(let param),
                .getEstimateCar(let param),
                .getHistoryInfo(let param),
                .getProductPage(let param),
                .getCategoryList(let param),
                .getProductDetail(let param),
                .getShoppingCartList(let param),
                .addShoppingCart(let param),
                .productOrder(let param),
                .getCurrentNum(let param),
                .productSubmit(let param),
                .productOrderDetail(let param),
                .myFavoriteProduct(let param),
                .cartDAddNum(let param),
                .removeAllCart(let param),
                .removeSingleCartGoods(let param),
//                .moreFlashCale(let param),
                .getFlashSale(let param),
                .carIntegrate(let param),
                .getListVerbose(let param),
                .carOrderGetLastInfo(let param),
                .cancelMember(let param),
                .getCouponcodeDataNew(let param),
                .consultationList(let param),
                .commonMmemberVerify(let param),
                .commonMemberAreaCode(let param),
                .shareActivities(let param),
                .couponCodePageV3(let param),
                .codeExchange(let param),
                .couponCodeCodeExchange(let param),
                .memberIntegralPage(let param),
                .indexPointsRule(let param),
                .myFavoritePage(let param),
                .myFavoriteProductPage(let param),
                .myCartListNum(let param),
                .bookingAvailabilitySelectDay(let param),
                .serverProductPage(let param),
                .bookingOrderManagerPage(let param),
                .bookingOrderManagerDetail(let param),
                .goonetcarSelectparameter(let param),
                .goonetcarUserdCarPage(let param),
                .goonetcarDetail(let param),
                .favorite(let param),
                .goonetcarUserdRecommand(let param),
                .bookingOrderManagerUpdate(let param),
                .getAppVersion(let param):
                return .requestParameters(parameters: param as! [String : Any], encoding: URLEncoding.default)
            
        case .cloudRegist(let param),
                .updateUserInfo(let param),
                .modifyPassword(let param),
                .usedcarOrder(let param),
                .recycleOrderSave(let param),
                .maintainOrderSave(let param),
                .productCollect(let param),
                .createServerOrder(let param),
                .memberRegister(let param),
                .browsingHistory(let param),
                .favoriteProduct(let param),
                .logoutAccount(let param),
                .bookingOrderManagerCreateServerOrder(let param),
                .login(let param):
            //参数放在Body里
            return .requestCompositeParameters(bodyParameters: param as! [String : Any],
                                               bodyEncoding: JSONEncoding.default,
                                               urlParameters: [:])
        case .ossUploadImage(let imageData):
            let formData = MultipartFormData(provider: .data(imageData),
                                             name: "file",
                                             fileName: "hangge.png", mimeType: "image/png")
            return .uploadCompositeMultipart([formData], urlParameters: [:])
        default:
            return .requestPlain
        }
    }
}

